package com.github.postsanf.yinian.activity;

import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.facebook.drawee.view.SimpleDraweeView;
import com.github.postsanf.yinian.BaseActivity;
import com.github.postsanf.yinian.R;
import com.github.postsanf.yinian.adapter.MCardEditGridLayoutAdapter;
import com.github.postsanf.yinian.bean.Tag;
import com.github.postsanf.yinian.constants.ACTIONs;
import com.github.postsanf.yinian.constants.CommonConstants;
import com.github.postsanf.yinian.constants.SelectedImg;
import com.github.postsanf.yinian.utils.UIHelper;
import com.github.postsanf.yinian.constants.YNSingleton;
import com.github.postsanf.yinian.randomlayout.DividerItemDecoration;
import com.github.postsanf.yinian.randomlayout.TwoWayView;
import com.github.postsanf.yinian.service.ModifyTypeService;
import com.github.postsanf.yinian.service.UpLoadService;
import com.github.postsanf.yinian.utils.DateTimePickDialogUtil;
import com.github.postsanf.yinian.utils.ImageOptHelper;
import com.github.postsanf.yinian.utils.SizeFormat;
import com.github.postsanf.yinian.utils.StringUtils;
import com.github.postsanf.yinian.widget.TagCloudLinkView;
import com.umeng.analytics.MobclickAgent;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MemoryCardEditActivity extends BaseActivity implements View.OnClickListener {
    public static final int TAKE_TAG = 2;
    public static final int TAKE_MIC = 3;
    public static final int TAKE_SYNC = 4;
    private List<String> tempUris;
    private TwoWayView McardEtwowaysView;
    private MCardEditGridLayoutAdapter mGridAdapter;
    private EditText mcarde_content_txt;
    private TextView mcarde_date_year;
    private TextView mcarde_date_mouth;
    private RelativeLayout mcarde_mic;
    private TextView mcarde_mic_tx;
    private EditText mcarde_location;
    public static ArrayList<Tag> tagList = new ArrayList<Tag>();
    private TagCloudLinkView uploadTag;
    private String micurl = "";
    private String gimid;
    private int groupId;
    private String contentstr;
    private String tagsStr;
    private String locationStr;
    private String timestr;
    private ProgressDialog mProgressDialog;             // 进度条
    private int isPush = 0;
    private int aIsOfficial = 0;// 默认不是官方相册
    private long upstorge;
    private boolean IstoSync;
    private ConnectivityManager mConnectivityManager;
    private NetworkInfo netInfo;
    SharedPreferences.Editor editor;
    private RelativeLayout detail_top;
    private InputMethodManager inputMethodManager;

    private LinearLayout ll_two_pic;
    private SimpleDraweeView iv_first_pic;
    private SimpleDraweeView iv_second_pic;
    private ScrollView scrollv;
    private RelativeLayout mcarde_morepic_twopic;
    private RelativeLayout mcarde_morepic;
    private RelativeLayout mr_bg;
    private int mictime;
    boolean mp3IsExist = false;
    private String edit;

    // 总长度
    private long getTotalLenth() {
        long totalSize = 0;
        for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
            String address = SelectedImg.mSelectedImage.get(i);
            File uploadImg = new File(address);
            long imgSize = uploadImg.length();
            totalSize += imgSize;
        }
        return totalSize;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_memory_card_edit);
        inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        registerBroadcastReceiver();
        initData();
        initView();
    }


    private void initData() {
        edit = getIntent().getStringExtra("edit");
        if (edit != null && edit.equals("edit")) {
            SelectedImg.mSelectedImage.clear();
            SelectedImg.mSelectedImage.addAll(YNSingleton.getInstance().getCurStatus().getUrl());
        }
        tempUris = SelectedImg.mSelectedImage;
        groupId = YNSingleton.getInstance().getCurAlbum().getGroupid();
        gimid = YNSingleton.getInstance().getCurAlbum().getGimid();
        aIsOfficial = StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0;
        editor = getSharedPreferences(ACTIONs.mynetwork, 0).edit();
    }

    private void initView() {
        //两张照片上下显示
        ll_two_pic = ((LinearLayout) findViewById(R.id.ll_two_pic));
        iv_first_pic = ((SimpleDraweeView) findViewById(R.id.iv_first_pic));
        iv_second_pic = ((SimpleDraweeView) findViewById(R.id.iv_second_pic));
        mcarde_morepic_twopic = ((RelativeLayout) findViewById(R.id.mcarde_morepic_twopic));
        scrollv = ((ScrollView) findViewById(R.id.scrollv));
        mcarde_morepic = ((RelativeLayout) findViewById(R.id.mcarde_morepic));
        mcarde_morepic_twopic.setOnClickListener(this);
        TextView mcardUpload = (TextView) findViewById(R.id.mcarde_upload);
        if (aIsOfficial == 1) {
            mcardUpload.setText("投稿");
        }
        IstoSync = getIntent().getBooleanExtra(ACTIONs.IstoSync, false);
        detail_top = (RelativeLayout) findViewById(R.id.detail_top);
        mcarde_content_txt = (EditText) findViewById(R.id.mcarde_content_txt);
        mcarde_content_txt.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        mcarde_content_txt.clearFocus();
        findViewById(R.id.mcarde_back).setOnClickListener(this);
        findViewById(R.id.mcarde_upload).setOnClickListener(this);
        findViewById(R.id.mcarde_date_layout).setOnClickListener(this);
        findViewById(R.id.mcarde_morepic).setOnClickListener(this);
        mr_bg = (RelativeLayout) findViewById(R.id.mr_bg);
        //点击空白区域隐藏键盘
        mr_bg.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                mr_bg.setFocusable(true);
                mr_bg.setFocusableInTouchMode(true);
                mr_bg.requestFocus();
                inputMethodManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                return false;
            }
        });
        mcarde_date_year = (TextView) findViewById(R.id.mcarde_date_year);
        mcarde_date_mouth = (TextView) findViewById(R.id.mcarde_date_mouth);
        mcarde_date_year.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        mcarde_date_mouth.setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        ((TextView) findViewById(R.id.mcarde_date_ri)).setTypeface(Typeface.createFromAsset(this.getAssets(), "fzqk.ttf"));
        String str = new SimpleDateFormat("yyyy-MM-dd").format(new Date(System.currentTimeMillis()));
        mcarde_date_year.setText(str.split("-")[0]);
        mcarde_date_mouth.setText(str.split("-")[1] + "." + str.split("-")[2]);
        mcarde_date_year.setTag(str);
        mcarde_location = (EditText) findViewById(R.id.mcarde_location);
        mcarde_location.clearFocus();
        mcarde_location.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mcarde_location.setCursorVisible(true);
            }
        });
        mcarde_mic = (RelativeLayout) findViewById(R.id.mcarde_mic);
        mcarde_mic_tx = (TextView) findViewById(R.id.mcarde_mic_tx);
        mcarde_mic.setOnClickListener(this);
        uploadTag = (TagCloudLinkView) findViewById(R.id.mcarde_content_tag_tx);
        if (edit != null && edit.equals("edit")) {
            mcarde_content_txt.setText(YNSingleton.getInstance().getCurStatus().getEtext());
            String strtime = YNSingleton.getInstance().getCurStatus().getEmemorytime().split(" ")[0];
            mcarde_date_year.setText(strtime.split("-")[0]);
            mcarde_date_year.setTag(strtime);
            mcarde_date_mouth.setText(strtime.split("-")[1] + "." + strtime.split("-")[2]);
            mcarde_location.setText(YNSingleton.getInstance().getCurStatus().getEplace());
            if (!StringUtils.isEmpty(YNSingleton.getInstance().getCurStatus().getEaudio())) {
                MainActivity.micpath = YNSingleton.getInstance().getCurStatus().getEaudio();
                String url = YNSingleton.getInstance().getCurStatus().getEaudio();
                micurl = url.substring(url.lastIndexOf("com") + 4, url.indexOf("mp3") + 3);
                mp3IsExist = true;
                mictime = getIntent().getIntExtra("mictime", 0);
                mcarde_mic_tx.setText(mictime + "“");
            }
            List<Tag> ts = YNSingleton.getInstance().getCurStatus().getTags();
            if (ts != null && ts.size() > 0) {
                tagList.clear();
                for (int j = 0; j < ts.size(); j++) {
                    if (!StringUtils.isEmpty(ts.get(j).getTagContent())) {
                        Tag tag = ts.get(j);
                        tag.setText(ts.get(j).getTagContent());
                        tagList.add(tag);
                        uploadTag.add(new Tag(j, tag.getText()));
                    }
                }
                if (tagList.size() > 0) {
                    uploadTag.drawTags(R.drawable.mycard_guide_tag_white, R.color.user_color_green, 12);
                } else {
                    uploadTag.add(new Tag(1000, "点击添加标签"));
                    uploadTag.drawTags(R.drawable.mycard_guide_tag_white, R.color.user_color_green, 12);
                }
            }
        } else {
            uploadTag.add(new Tag(1000, "点击添加标签"));
            uploadTag.drawTags(R.drawable.mycard_guide_tag_white, R.color.user_color_green, 12);
        }
        uploadTag.setOnTagSelectListener(new TagCloudLinkView.OnTagSelectListener() {
            @Override
            public void onTagSelected(Tag tag, int position, View tagView, TextView textView) {
                startActivityForResult(new Intent(MemoryCardEditActivity.this, MemoryCardLabel.class), TAKE_TAG);
            }
        });
        McardEtwowaysView = (TwoWayView) findViewById(R.id.mcarde_twoways_view);
        // McardEtwowaysView.setScrollContainer(false);
        McardEtwowaysView.setKeepScreenOn(false);
        McardEtwowaysView.addItemDecoration(new DividerItemDecoration(getResources().getDrawable(R.drawable.mcard_divider)));
        mGridAdapter = new MCardEditGridLayoutAdapter(MemoryCardEditActivity.this, McardEtwowaysView, tempUris);
        McardEtwowaysView.setAdapter(mGridAdapter);
        if (tempUris.size() == 1) {
            scrollv.setVisibility(View.VISIBLE);
            ll_two_pic.setVisibility(View.GONE);
            mcarde_morepic_twopic.setVisibility(View.GONE);
            mcarde_morepic.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) detail_top.getLayoutParams();
            lp.bottomMargin = UIHelper.dip2px(MemoryCardEditActivity.this, 50);
            detail_top.setLayoutParams(lp);
        } else if (tempUris.size() == 2) {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) detail_top.getLayoutParams();
            lp.bottomMargin = UIHelper.dip2px(MemoryCardEditActivity.this, 80);
            detail_top.setLayoutParams(lp);
            scrollv.setVisibility(View.GONE);
            ll_two_pic.setVisibility(View.VISIBLE);
            mcarde_morepic_twopic.setVisibility(View.VISIBLE);
            mcarde_morepic.setVisibility(View.GONE);
            if (tempUris.get(0).startsWith("http")) {
                ImageOptHelper.showFrescoImg(Uri.parse(tempUris.get(0)), iv_first_pic, MemoryCardEditActivity.this);
            } else {
                ImageOptHelper.showFrescoImg(Uri.parse("file://" + tempUris.get(0)), iv_first_pic, MemoryCardEditActivity.this);
            }
            if (tempUris.get(1).startsWith("http")) {
                ImageOptHelper.showFrescoImg(Uri.parse(tempUris.get(1)), iv_second_pic, MemoryCardEditActivity.this);
            } else {
                ImageOptHelper.showFrescoImg(Uri.parse("file://" + tempUris.get(1)), iv_second_pic, MemoryCardEditActivity.this);
            }
        } else {
            scrollv.setVisibility(View.VISIBLE);
            ll_two_pic.setVisibility(View.GONE);
            mcarde_morepic_twopic.setVisibility(View.GONE);
            mcarde_morepic.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) detail_top.getLayoutParams();
            lp.bottomMargin = UIHelper.dip2px(MemoryCardEditActivity.this, 20);
            detail_top.setLayoutParams(lp);
        }
    }

//    protected void addLocation() {
//        RelativeLayout nameLayout = (RelativeLayout) getLayoutInflater()
//                .inflate(R.layout.add_location_dialog, null);
//        final Dialog nameDialog = new Dialog(MemoryCardEditActivity.this, R.style.dialog);
//        nameDialog.addContentView(nameLayout, new ViewGroup.LayoutParams(-2, -2));
//        nameDialog.show();
//        final EditText dialogET = (EditText) nameLayout
//                .findViewById(R.id.dialog_edit);
//        ImageView dialogClean = (ImageView) nameLayout
//                .findViewById(R.id.dialog_edit_clean);
//        dialogClean.setOnClickListener(new View.OnClickListener() {
//            public void onClick(View v) {
//                dialogET.setText("");
//            }
//        });
//        nameLayout.findViewById(R.id.btn_ok).setOnClickListener(
//                new View.OnClickListener() {
//                    public void onClick(View v) {
//                        String tag = dialogET.getText().toString();
//                        if (tag == null || tag.equals("")) {
//                            Toast.makeText(MemoryCardEditActivity.this, "不能为空", Toast.LENGTH_SHORT)
//                                    .show();
//                            return;
//                        }
//                        mcarde_location.setText(tag);
//                        if (inputMethodManager.isActive()) {
//                            inputMethodManager.toggleSoftInput(
//                                    InputMethodManager.SHOW_IMPLICIT,
//                                    InputMethodManager.HIDE_NOT_ALWAYS);
//                        }
//                        nameDialog.dismiss();
//                    }
//                });
//        nameLayout.findViewById(R.id.btn_cancel).setOnClickListener(
//                new View.OnClickListener() {
//                    public void onClick(View v) {
//                        if (inputMethodManager.isActive()) {
//                            inputMethodManager.toggleSoftInput(
//                                    InputMethodManager.SHOW_IMPLICIT,
//                                    InputMethodManager.HIDE_NOT_ALWAYS);
//                        }
//                        nameDialog.cancel();
//                    }
//                });
//    }


    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        tempUris = SelectedImg.mSelectedImage;
        updateImgs();
    }

    // 图片列表更新
    private void updateImgs() {
        mGridAdapter.notifyDataSetChanged();
        if (tempUris.size() == 1) {
            scrollv.setVisibility(View.VISIBLE);
            ll_two_pic.setVisibility(View.GONE);
            mcarde_morepic_twopic.setVisibility(View.GONE);
            mcarde_morepic.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) detail_top.getLayoutParams();
            lp.bottomMargin = UIHelper.dip2px(MemoryCardEditActivity.this, 50);
            detail_top.setLayoutParams(lp);
        } else if (tempUris.size() == 2) {
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) detail_top.getLayoutParams();
            lp.bottomMargin = UIHelper.dip2px(MemoryCardEditActivity.this, 80);
            detail_top.setLayoutParams(lp);
            scrollv.setVisibility(View.GONE);
            ll_two_pic.setVisibility(View.VISIBLE);
            mcarde_morepic_twopic.setVisibility(View.VISIBLE);
            mcarde_morepic.setVisibility(View.GONE);
            if (tempUris.get(0).startsWith("http")) {
                ImageOptHelper.showFrescoImg(Uri.parse(tempUris.get(0)), iv_first_pic, MemoryCardEditActivity.this);
            } else {
                ImageOptHelper.showFrescoImg(Uri.parse("file://" + tempUris.get(0)), iv_first_pic, MemoryCardEditActivity.this);
            }
            if (tempUris.get(1).startsWith("http")) {
                ImageOptHelper.showFrescoImg(Uri.parse(tempUris.get(1)), iv_second_pic, MemoryCardEditActivity.this);
            } else {
                ImageOptHelper.showFrescoImg(Uri.parse("file://" + tempUris.get(1)), iv_second_pic, MemoryCardEditActivity.this);
            }
        } else {
            scrollv.setVisibility(View.VISIBLE);
            ll_two_pic.setVisibility(View.GONE);
            mcarde_morepic_twopic.setVisibility(View.GONE);
            mcarde_morepic.setVisibility(View.VISIBLE);
            RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) detail_top.getLayoutParams();
            lp.bottomMargin = UIHelper.dip2px(MemoryCardEditActivity.this, 20);
            detail_top.setLayoutParams(lp);
        }
    }

    // 广播接收
    private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTIONs.updataMcardEdit:
                    tempUris = SelectedImg.mSelectedImage;
                    updateImgs();
                    break;
                case ACTIONs.actionCloseAlbum:
                    finish();
                    break;
                case ACTIONs.actionMIcText:
                    mp3IsExist = intent.getBooleanExtra("isOK", false);
                    micurl = intent.getStringExtra("micUrl");
                    if (!StringUtils.isEmpty(micurl)) {
                        if (mp3IsExist) {
                            mcarde_mic_tx.setText(MicActivity.timer + "“");
                        } else {
                            mcarde_mic_tx.setText("点击录制");
                        }
                    } else {
                        if (StringUtils.isEmpty(intent.getStringExtra("micpath"))) {
                            mcarde_mic_tx.setText("点击录制");
                        } else {
                            String url = intent.getStringExtra("micpath");
                            String newurl = url.substring(url.lastIndexOf("com") + 4, url.indexOf("mp3") + 3);
                            micurl = newurl;
                        }
                    }
                    break;
            }
        }
    };

    //注册广播
    private void registerBroadcastReceiver() {
        IntentFilter myIntentFilter = new IntentFilter();
        myIntentFilter.addAction(ACTIONs.updataMcardEdit);
        myIntentFilter.addAction(ACTIONs.actionCloseAlbum);
        myIntentFilter.addAction(ACTIONs.actionMIcText);
        this.registerReceiver(mBroadcastReceiver, myIntentFilter);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.unregisterReceiver(mBroadcastReceiver);
        SelectedImg.mSelectedImage.clear();
        tagList.clear();
        MicActivity.mMp3FileName = "";
    }

    private boolean local = false;

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.mcarde_back:
                new AlertDialog.Builder(MemoryCardEditActivity.this).setMessage("确定不要这张记录卡片了吗？")
                        .setPositiveButton(R.string.yn_app_ok, new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int whichButton) {
                                finish();
                            }
                        }).setNegativeButton(R.string.yn_app_cancel, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int whichButton) {
                    }
                }).show();
                break;
            case R.id.mcarde_upload:
                if (tempUris.size() == 0) {
                    showToast("选择图片上传");
                    return;
                }
                contentstr = mcarde_content_txt.getText().toString();
                timestr = mcarde_date_year.getTag().toString();
                if (tagList.size() > 0) {
                    StringBuilder builder = new StringBuilder();
                    for (int j = 0; j < tagList.size(); j++) {
                        builder.append(tagList.get(j).getText() + "&nbsp");
                    }
                    String taglistr = builder.toString();
                    tagsStr = taglistr.substring(0, taglistr.length() - 5);
                } else {
                    tagsStr = "";
                }
                //语音micurl
                locationStr = mcarde_location.getText().toString();
                long totalSize = 0;
                for (int i = 0; i < SelectedImg.mSelectedImage.size(); i++) {
                    String address = SelectedImg.mSelectedImage.get(i);
                    if (!address.startsWith("http")) {
                        File uploadImg = new File(address);
                        long imgSize = uploadImg.length();
                        totalSize += imgSize;
                        local = true;
                    }
                }
                upstorge = totalSize;
                String fsize = SizeFormat.formatSize(totalSize);
                //是否同步
                if (!IstoSync) {
                    mConnectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    netInfo = mConnectivityManager.getActiveNetworkInfo();
                    if (netInfo != null && netInfo.isAvailable()) {
                        if (netInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                            //WiFi网络
                            if (edit != null && edit.equals("edit")) {
                                moidfyUpload(false);
                            } else {
                                doUpImg(false);
                            }
                        } else if (netInfo.getType() == ConnectivityManager.TYPE_MOBILE) {
                            //3g网络
                            int netfrist = getSharedPreferences(ACTIONs.mynetwork, 0).getInt(ACTIONs.networkFrist, 0);
                            String nettype = getSharedPreferences(ACTIONs.mynetwork, 0).getString(ACTIONs.networkType, "");
                            if (!nettype.equals("") && nettype.equals(ACTIONs.network3GWIFI)) {
                                if (edit != null && edit.equals("edit")) {
                                    moidfyUpload(false);
                                } else {
                                    doUpImg(false);
                                }
                            } else {
                                if (netfrist == 0) {
                                    FristNetWork(fsize);
                                    editor.putInt(ACTIONs.networkFrist, 1);
                                    editor.commit();
                                } else {
                                    SecondNetWork(fsize);
                                }
                            }
                        }
                    }
                    // doUpImg(false);
                } else {
                    syncUpImg(false);
                }
                String gtype = YNSingleton.getInstance().getCurAlbum().getGtype();
                if (gtype!=null){
                    if (gtype.equals("6") || gtype.equals("7") || gtype.equals("8")) {
                        startService(new Intent(MemoryCardEditActivity.this, ModifyTypeService.class));
                    }
                }
                break;
            case R.id.mcarde_morepic:
                Intent intent = new Intent(MemoryCardEditActivity.this, MemoryCardPicActivity.class);
                intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intent);
                break;
            case R.id.mcarde_date_layout:
                String tttime = mcarde_date_year.getTag().toString();
                DateTimePickDialogUtil dateTimePicKDialog = new DateTimePickDialogUtil(this, tttime);
                dateTimePicKDialog.dateTimePicKDialog(mcarde_date_year, mcarde_date_mouth);
                break;
            case R.id.mcarde_mic:
                Intent micIntent = new Intent(MemoryCardEditActivity.this, MicActivity.class);
                micIntent.putExtra("mp3IsExist", mp3IsExist);
                micIntent.putExtra("micpath", MainActivity.micpath);
                micIntent.putExtra("mictime", mictime);
                startActivityForResult(micIntent, TAKE_MIC);
                break;
            case R.id.mcarde_content_tag_tx:
                startActivityForResult(new Intent(MemoryCardEditActivity.this, MemoryCardLabel.class), TAKE_TAG);
                break;
//            case R.id.mcarde_location:
//                addLocation();
//                break;
            case R.id.mcarde_morepic_twopic:
                Intent intentTwopic = new Intent(MemoryCardEditActivity.this, MemoryCardPicActivity.class);
                intentTwopic.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
                startActivity(intentTwopic);
                break;
        }
    }

    private void syncUpImg(boolean isPause) {
        Intent syncIntent = new Intent(MemoryCardEditActivity.this, CardSyncUploadActivity.class);
        syncIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        syncIntent.putExtra(ACTIONs.aGid, groupId + "");
        syncIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
        syncIntent.putExtra(ACTIONs.aPush, isPush);
        syncIntent.putExtra(ACTIONs.aIsOfficial, aIsOfficial);
        syncIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        syncIntent.putExtra(ACTIONs.aContent, contentstr);
        syncIntent.putExtra(ACTIONs.aisPause, isPause);
        syncIntent.putExtra(ACTIONs.upstorage, String.valueOf(SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB)));
        syncIntent.putExtra(ACTIONs.upismemorycard, 1);
        syncIntent.putExtra(ACTIONs.uptags, tagsStr);
        syncIntent.putExtra(ACTIONs.upaudio, micurl);
        syncIntent.putExtra(ACTIONs.upmemorytime, timestr);
        syncIntent.putExtra(ACTIONs.upplace, locationStr);
        syncIntent.putExtra(ACTIONs.upaudiotime, "");
        syncIntent.putExtra(ACTIONs.upcoverUrl, "");
        startActivityForResult(syncIntent, TAKE_SYNC);
    }

    private void doUpImg(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.actionPublishPhoto);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, groupId + "");
        mIntent.putExtra(ACTIONs.aGimid, gimid);
        mIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
        mIntent.putExtra(ACTIONs.aPush, isPush);
        mIntent.putExtra(ACTIONs.aIsOfficial, aIsOfficial);
        mIntent.putExtra(ACTIONs.aGname, YNSingleton.getInstance().getCurAlbum().getGname());
        mIntent.putExtra(ACTIONs.aContent, contentstr);
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        mIntent.putExtra(ACTIONs.upismemorycard, 1);
        mIntent.putExtra(ACTIONs.uptags, tagsStr);
        mIntent.putExtra(ACTIONs.upaudio, micurl);
        mIntent.putExtra(ACTIONs.upmemorytime, timestr);
        mIntent.putExtra(ACTIONs.upplace, locationStr);
        mIntent.putExtra(ACTIONs.upaudiotime, "");
        mIntent.putExtra(ACTIONs.upcoverUrl, "");
        startService(mIntent);
        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_TAG:
                if (data != null) {
                    if (uploadTag.getTags().size() == 1) {
                        uploadTag.remove(0);
                    } else {
                        while (true) {
                            for (int i = 0; i < uploadTag.getTags().size(); i++) {
                                uploadTag.remove(i);
                            }
                            if (uploadTag.getTags().size() == 0) {
                                break;
                            }
                        }
                    }
                    for (int j = 0; j < tagList.size(); j++) {
                        uploadTag.add(new Tag(j, tagList.get(j).getText()));
                    }
                    uploadTag.drawTags(R.drawable.mycard_guide_tag_white, R.color.user_color_green, 12);
                }
                break;
            case TAKE_MIC:
                if (data != null) {
                    micurl = data.getStringExtra("micUrl");
                    Log.i("xjs", "TAKE_MIC=+mp3IsExist=>" + mp3IsExist);
                    if (!StringUtils.isEmpty(micurl)) {
                        mp3IsExist = data.getBooleanExtra("isOK", false);
                        if (mp3IsExist) {
                            mcarde_mic_tx.setText(MicActivity.timer + "“");
                        } else {
                            mcarde_mic_tx.setText("点击录制");
                        }
                    } else {
                        if (StringUtils.isEmpty(data.getStringExtra("micpath"))) {
                            mcarde_mic_tx.setText("点击录制");
                        } else {
                            String url = data.getStringExtra("micpath");
                            String newurl = url.substring(url.lastIndexOf("com") + 4, url.indexOf("mp3") + 3);
                            micurl = newurl;
                        }
                    }
                }
                break;
            case TAKE_SYNC:
                if (data != null) {
                    finish();
                }
                break;
        }
    }


    public void SecondNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText(">_< 您关闭了使用流量上传开关，你在使用3g/4g网络环境下，这会消耗您" + fsize + "流量，确定继续上传吗？");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("取消");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("仅一次");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(false);
                } else {
                    doUpImg(false);
                }
                dlg.cancel();
            }
        });
    }

    public void FristNetWork(String fsize) {
        final AlertDialog dlg = new AlertDialog.Builder(this).create();
        dlg.show();
        Window window = dlg.getWindow();
        window.setContentView(R.layout.publish_network_dialog);
        TextView tt = (TextView) window.findViewById(R.id.pp_title);
        tt.setText("您现在处于移动网络环境下，将消耗" + fsize + "流量，是否使用流量继续上传?");
        final TextView ok = (TextView) window.findViewById(R.id.btn_ep_ok);
        ok.setText("不允许");
        ok.setBackgroundColor(getResources().getColor(R.color.white));
        ok.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(true);
                } else {
                    doUpImg(true);
                }
                dlg.cancel();
            }
        });
        final TextView cancel = (TextView) window
                .findViewById(R.id.btn_ep_cancel);
        cancel.setText("确定");
        cancel.setBackgroundColor(getResources().getColor(R.color.white));
        cancel.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                editor.putString(ACTIONs.networkType, ACTIONs.network3GWIFI);
                editor.commit();
                if (edit != null && edit.equals("edit")) {
                    moidfyUpload(true);
                } else {
                    doUpImg(true);
                }
                dlg.cancel();
            }
        });
    }

    private void moidfyUpload(boolean isPause) {
        mProgressDialog = ProgressDialog.show(this, "", CommonConstants.TIP_LOAD_UP);
        Intent mIntent = new Intent(this, UpLoadService.class);
        mIntent.setAction(ACTIONs.modifyStatus);
        mIntent.putExtra(ACTIONs.aUid, application.getCurID() + "");
        mIntent.putExtra(ACTIONs.aGid, groupId + "");
        mIntent.putExtra(ACTIONs.aGimid, gimid);
        mIntent.putExtra(ACTIONs.aEid, YNSingleton.getInstance().getCurStatus().getEid() + "");
        mIntent.putExtra(ACTIONs.aContent, mcarde_content_txt.getText().toString().trim());
        mIntent.putExtra(ACTIONs.aEplace, mcarde_location.getText().toString());
        mIntent.putExtra(ACTIONs.upmemorytime, timestr);
        mIntent.putExtra(ACTIONs.upaudio, micurl);
        mIntent.putExtra(ACTIONs.upcoverUrl, "");
        mIntent.putExtra(ACTIONs.uptags, tagsStr);
        mIntent.putExtra(ACTIONs.upgname, YNSingleton.getInstance().getCurAlbum().getGname());
        mIntent.putExtra(ACTIONs.aType, StringUtils.isOfficialGroup(YNSingleton.getInstance().getCurAlbum().getGtype()) ? 1 : 0);
//        mIntent.putExtra(ACTIONs.aPush, isPush);
        if (local) {
            mIntent.putExtra(ACTIONs.upstorage, SizeFormat.formatDouble(upstorge, SizeFormat.FZ_KB));
        } else {
            mIntent.putExtra(ACTIONs.upstorage, YNSingleton.getInstance().getCurStatus().geteStoragePlace());
        }
        mIntent.putExtra(ACTIONs.picType, "recordCard");
        mIntent.putExtra(ACTIONs.aisPause, isPause);
        startService(mIntent);

        startActivity(new Intent(this, UpLoadActivity.class).putExtra(ACTIONs.IstoSetWifi, isPause));
        Intent upIntent = new Intent(ACTIONs.actionCloseAlbum);
        upIntent.putExtra(ACTIONs.aIsClearSelect, 1);
        sendBroadcast(upIntent);
        mProgressDialog.dismiss();
    }

    private long fristTime;

    // 友盟统计
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getSimpleName());
        MobclickAgent.onResume(this);
        fristTime = System.currentTimeMillis();
    }

    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getSimpleName());
        MobclickAgent.onPause(this);
        Intent intent = new Intent(ACTIONs.record);
        intent.putExtra("key", "recordCard_3");
        intent.putExtra("value", new Long(System.currentTimeMillis() - fristTime).intValue());
        sendBroadcast(intent);
    }
}
